using System.Runtime.CompilerServices;
using UnityEngine;
using Unity.Burst;

namespace DA.AnimGraph {
    [BurstCompile]
    public static class AnimMath {
        public const float NEAR_ZERO_VALUE = 0.000001f;

        [BurstCompile]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool IsNearZero(this float self) {
            return self * self < NEAR_ZERO_VALUE;
        }

        [BurstCompile]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static bool IsNear(this float self, float other) {
            self = self - other;
            return self * self < NEAR_ZERO_VALUE;
        }

        /// <summary>
        /// 在self的基础上消耗input的数量，
        /// 返回: 消耗完后 self 的值，
        /// input变为剩余值，
        /// self不变
        /// </summary>
        [BurstCompile]
        public static float Reduce(this float self, ref float input) {
            var newValue = self - input;
            if (newValue.IsNearZero()) {
                input = 0;
                return 0;
            } else if (newValue > 0) {
                input = 0;
                return newValue;
            } else {
                input = -newValue;
                return 0;
            }
        }

        /// <summary>
        /// 反向 lerp
        /// 返回百分比
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float RevertLerp(float value, float a, float b) {
            return (value - a) / (b - a);
        }

        // 计算数量积
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static float Cross(in Vector2 a, in Vector2 b) {
            return a.x * b.y - a.y * b.x;
        }
    }
}
